/*
 * @Description: 权限验证
 * @Author: HuiSir<https://gitee.com/huisir001>
 * @Date: 2025-08-15 08:59:18
 * @LastEditTime: 2025-08-15 10:08:33
 */
import type { Directive, DirectiveBinding } from "vue";
import { useAdminStore } from "@/store";

// 使用，传入功能权限code
// v-permission="abc"
// v-permission="['abc','def]" 包含一个就有权限
// v-permission:disabled=""  禁用

const vPermission: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    validatePermission(el, binding);
  },
  updated(el: HTMLElement, binding: DirectiveBinding) {
    validatePermission(el, binding);
  },
};

function validatePermission(
  el: HTMLElement,
  binding: DirectiveBinding<string | string[]>
) {
  const adminStore = useAdminStore();
  const permissionValue = binding.value;

  // 参数校验
  if (!permissionValue) throw new Error("必须提供权限标识");

  // 处理权限类型
  const permissions = Array.isArray(permissionValue)
    ? permissionValue
    : [permissionValue as string];

  // 获取用户权限
  const funcPermCodes = adminStore.funcPermCodes;
  const hasPermission = permissions.some((code) =>
    funcPermCodes.includes(code)
  );

  // 处理禁用状态
  if (binding.modifiers.disabled) {
    // 设置半透明样式（强制覆盖）
    el.style.setProperty("opacity", "0.5", "important");

    // 禁止鼠标事件
    el.style.setProperty("pointer-events", "none", "important");

    // 修改鼠标样式为禁止图标
    el.style.setProperty("cursor", "not-allowed", "important");

    // 阻止所有事件冒泡和默认行为
    const stopPropagation = (e: Event) => {
      e.preventDefault();
      e.stopPropagation();
    };

    // 绑定所有事件监听器
    const events = ["click", "mousedown", "touchstart", "keydown"];
    events.forEach((eventType) => {
      el.addEventListener(eventType, stopPropagation as EventListener);
    });

    // 保存事件绑定信息用于解绑
    el.dataset.eventsBound = "true";
  } else {
    // 有权限时移除事件监听
    if (el.dataset.eventsBound === "true") {
      const events = ["click", "mousedown", "touchstart", "keydown"];
      events.forEach((eventType) => {
        el.removeEventListener(eventType, () => {});
      });
      el.dataset.eventsBound = "false";
    }
  }

  // 无权限时移除节点（保持原有逻辑）
  if (!hasPermission && !binding.modifiers.disabled) {
    el.parentNode?.removeChild(el);
  }
}

export default vPermission;
